package com.finger.forest;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.custom.MyMarkerView;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.GridUserModel;
import com.finger.forest.model.Patrol;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.XAxisValueFormatter;
import com.finger.forest.utils.encode.PrefsUtil;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 巡护统计
 */
public class PatrolStaticActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "PatrolStaticActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 刷新按钮
     */
    @BindView(R.id.btn_right)
    ImageView rightBtn;

    /**
     * 行政区划
     */
    @BindView(R.id.tv_xzqh)
    TextView xzqhTv;

    /**
     * 责任区
     */
    @BindView(R.id.tv_zrq)
    TextView zrqTv;

    /**
     * 责任人
     */
    @BindView(R.id.tv_zrr)
    TextView zrrTv;

    /**
     * 开始日期
     */
    @BindView(R.id.tv_static_start)
    TextView staticStartTv;

    /**
     * 结束日期
     */
    @BindView(R.id.tv_static_end)
    TextView staticEndTv;

    protected BarChart barChart;
    protected LineChart chart;
    protected LineChart chart2;

    private String[] leaves = new String[]{"六安", "合肥"};
    private String[] zrq = new String[]{"责任区1", "责任区2"};
    private String[] zrr = new String[]{"责任人1", "责任人2"};

    private Calendar todayDate;
    private Calendar selectedDate;
    private Calendar startDate;
    private Calendar endDate;

    /**
     * 巡护发现数据（柱状图）
     */
    List<BarEntry> list = new ArrayList<>();

    /**
     * 巡护时长、里程数据
     */
    List<Patrol> patrolList = new ArrayList<>();

    /**
     * 巡护时长数据（折线图）
     */
    List<Entry> listH = new ArrayList<>();

    /**
     * 巡护里程数据（折线图）
     */
    List<Entry> listM = new ArrayList<>();

    @Override
    protected int setView() {
        return R.layout.activity_patrol_static;
    }

    @Override
    protected void receiveData() {
        mLeaveItems.clear();
        mLeaveItems.addAll(Arrays.asList(leaves));

        mZrqItems.clear();
        mZrqItems.addAll(Arrays.asList(zrq));

        //查询责任人
        presenter.loadUserManager(new HashMap<>());
    }

    @Override
    protected void initializeView() {
        barChart = findViewById(R.id.chart0);
        initBarChart0(true);

        chart = findViewById(R.id.chart1);
        initBarChart();

        chart2 = findViewById(R.id.chart2);
        initBarChart2();

        todayDate = Calendar.getInstance();
        selectedDate = Calendar.getInstance();
        startDate = Calendar.getInstance();
        endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(2018, 0, 1);
        endDate.set(2040, 0, 1);

        //初始化查询日期
        staticEndTv.setText(DateUtil.dateToStr(DateUtil.DATE_FORMAT));
        todayDate.set(Calendar.DAY_OF_MONTH, todayDate.get(Calendar.DAY_OF_MONTH)-7);
        staticStartTv.setText(new SimpleDateFormat(DateUtil.DATE_FORMAT).format(todayDate.getTime()));
    }

    private void initBarChart0(boolean boo) {
        //设置条形数据
        barChart.getDescription().setEnabled(false);
        barChart.getLegend().setEnabled(false);//图例
        barChart.setData(getBarData(boo));
        barChart.getAxisRight().setEnabled(false);

        //X轴
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//x轴位置
        xAxis.enableGridDashedLine(10f, 10f, 0f);//x轴背景线
        xAxis.setLabelRotationAngle(60);//x轴坐标值倾斜度数
        xAxis.setLabelCount(9);//x轴显示坐标数
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                String xValue = "";
                switch ((int) value){
                    case 1: xValue = "有害生物";
                        break;
                    case 2: xValue = "盗砍乱伐";
                        break;
                    case 3: xValue = "毁林开垦";
                        break;
                    case 4: xValue = "乱捕乱猎";
                        break;
                    case 5: xValue = "牲畜毁林";
                        break;
                    case 6: xValue = "自然灾害";
                        break;
                    case 7: xValue = "野生动物";
                        break;
                    case 8: xValue = "野生植物";
                        break;
                    default: xValue = "其他";
                }
                return xValue;
            }
        });

        //Y轴
        YAxis yAxis = barChart.getAxisLeft();
        yAxis.setAxisMinimum(0f);
        yAxis.enableGridDashedLine(10f, 10f, 0f);

    }

    public BarData getBarData(boolean boo) {
        int maxX = 10;
        //创建集合，存放每个柱子的数据
        /*List<BarEntry> list = new ArrayList<>();*/
        if (boo){
            for (int i = 1; i < maxX; i++) {
                //一个BarEntry就是一个柱子的数据对象
                BarEntry barEntry = new BarEntry(i, 0);
                list.add(barEntry);
            }
        }
        //创建BarDateSet对象，其实就是一组柱形数据
        BarDataSet barSet = new BarDataSet(list, "图例");
        //设置柱形的颜色
        barSet.setColor(getColor(R.color.colorBlueTop));
        //设置是否显示柱子上面的数值
        barSet.setDrawValues(true);
        //设置柱子阴影颜色
        barSet.setBarShadowColor(Color.GRAY);
        //创建集合，存放所有组的柱形数据
        List<IBarDataSet> dataSets = new ArrayList<>();
        dataSets.add(barSet);
        BarData barData = new BarData(dataSets);
        return barData;
    }


    @Override
    protected void loadDataFromServer() {

    }

    private void initBarChart() {
        chart.setBackgroundColor(Color.WHITE);
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(true);
        chart.setDrawGridBackground(false);
        chart.getLegend().setEnabled(false);//图例
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);

        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view, 1);
        mv.setChartView(chart);
        chart.setMarker(mv);

        //X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelRotationAngle(60);//x轴坐标值倾斜度数
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
            return patrolList.get((int)value).getCreateDate();
            }
        });

        YAxis yAxis = chart.getAxisLeft();
        //设置Y轴从0开始
        yAxis.setStartAtZero(true);
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        chart.getAxisRight().setEnabled(false);

        //获取数据
        setData();
    }

    private void setData() {
        LineDataSet set1 = new LineDataSet(listH, "");
        set1.setDrawIcons(false);
        set1.enableDashedLine(10f, 5f, 0f);
        set1.setColor(Color.BLACK);
        set1.setCircleColor(Color.BLACK);
        set1.setLineWidth(1f);
        set1.setCircleRadius(2f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setDrawFilled(true);
        //设置填充
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
        set1.setFillDrawable(drawable);

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1);

        LineData data = new LineData(dataSets);
        chart.setData(data);
    }

    private void initBarChart2() {
        chart2.setBackgroundColor(Color.WHITE);
        chart2.getDescription().setEnabled(false);
        chart2.setTouchEnabled(true);
        chart2.setDrawGridBackground(false);
        chart2.getLegend().setEnabled(false);//图例
        chart2.setDragEnabled(true);
        chart2.setScaleEnabled(true);
        chart2.setPinchZoom(true);

        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view, 2);
        mv.setChartView(chart2);
        chart2.setMarker(mv);

        //X轴
        XAxis xAxis = chart2.getXAxis();
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelRotationAngle(60);//x轴坐标值倾斜度数
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return patrolList.get((int)value).getCreateDate();
            }
        });

        YAxis yAxis = chart2.getAxisLeft();
        //设置Y轴从0开始
        yAxis.setStartAtZero(true);
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        chart2.getAxisRight().setEnabled(false);

        //获取数据
        setData2();
    }

    private void setData2() {
        LineDataSet set1 = new LineDataSet(listM, "");
        set1.setDrawIcons(false);
        set1.enableDashedLine(10f, 5f, 0f);
        set1.setColor(Color.BLACK);
        set1.setCircleColor(Color.BLACK);
        set1.setLineWidth(1f);
        set1.setCircleRadius(2f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setDrawFilled(true);
        //设置填充
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
        set1.setFillDrawable(drawable);

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1);

        LineData data = new LineData(dataSets);
        chart2.setData(data);
    }

    @OnClick({R.id.btn_back, R.id.tv_xzqh, R.id.tv_zrq, R.id.tv_zrr, R.id.tv_static_start, R.id.tv_static_end
            , R.id.btn_right})
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //刷新
                case R.id.btn_right:
                    refreshDate();
                    break;

                //行政区划
                case R.id.tv_xzqh:
                    loadXzqh();
                    break;

                //责任区
                case R.id.tv_zrq:
                    loadZrq();
                    break;

                //责任人
                case R.id.tv_zrr:
                    loadZrr();
                    break;

                //开始日期
                case R.id.tv_static_start:
                    //时间选择器
                    TimePickerView pvTimeStart = new TimePickerBuilder(PatrolStaticActivity.this, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            staticStartTv.setText(DateUtil.dateToStr(date));
                        }
                    })
                            .setDate(selectedDate)
                            .setRangDate(startDate, endDate)//起始终止年月日设定
                            .build();
                    pvTimeStart.show();
                    break;

                //结束日期
                case R.id.tv_static_end:
                    //时间选择器
                    TimePickerView pvTimeEnd = new TimePickerBuilder(PatrolStaticActivity.this, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            staticEndTv.setText(DateUtil.dateToStr(date));
                        }
                    })
                            .setDate(selectedDate)
                            .setRangDate(startDate, endDate)//起始终止年月日设定
                            .build();
                    pvTimeEnd.show();
                    break;

                default:
                    break;
            }
        }
    }

    private void refreshDate(){
        Map<String,Object> findMap = new HashMap<>();
        findMap.put("queryId", zrrTv.getTag().toString());
        findMap.put("gridUserIds", zrrTv.getTag().toString());
        findMap.put("beginTime", staticStartTv.getText().toString());
        findMap.put("endTime", staticEndTv.getText().toString());
        //查询巡护发现集合
        presenter.queryPatrolFind(findMap);
        //查询巡护时长、里程
        presenter.queryPatrolInfo(findMap);
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            //用户列表
            case ResponseTag.USER_MANAGER:
                List<GridUserModel> userManagerModelList = (List<GridUserModel>) model;
                if (null != userManagerModelList && userManagerModelList.size() > 0) {
                    mZrrItems.clear();
                    mZrrItems.addAll(userManagerModelList);
                    //初始化责任人查询条件
                    zrrTv.setText(userManagerModelList.get(0).getName());
                    zrrTv.setTag(userManagerModelList.get(0).getId());
                }

                refreshDate();
                break;

            //巡护发现
            case ResponseTag.QUERY_PATRAL_FIND:
                list.clear();
                List<Map<String,Object>> findList = (List<Map<String,Object>>) model;
                for (int i = 0; i < findList.size(); i++) {
                    Map<String,Object> mapObj = findList.get(i);
                    //一个BarEntry就是一个柱子的数据对象
                    BarEntry barEntry = new BarEntry(i+1, Integer.parseInt(mapObj.get("y").toString()));
                    list.add(barEntry);
                }
                barChart.clear();
                initBarChart0(false);
                break;

            //巡护时长、里程
            case ResponseTag.QUERY_PATRAL_INFO:
                patrolList = (List<Patrol>) model;
                listH.clear();
                listM.clear();
                for (int i = 0; i < patrolList.size(); i++) {
                    Patrol patrolObj = patrolList.get(i);
                    Entry entryH = new Entry(i, Float.parseFloat(patrolObj.getDuration()==null?"0":patrolObj.getDuration().toString()));
                    listH.add(entryH);
                    Entry entryM = new Entry(i, Float.parseFloat(patrolObj.getMileage()==null?"0":patrolObj.getMileage().toString()));
                    listM.add(entryM);
                }
                chart.clear();
                initBarChart();
                chart2.clear();
                initBarChart2();
                break;
        }

    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    private OptionsPickerView pvLeaveOptions;

    private int mLeavePosition;

    private List<String> mLeaveItems = new ArrayList<>();
    private List<String> mZrqItems = new ArrayList<>();
    private List<GridUserModel> mZrrItems = new ArrayList<>();

    private void loadXzqh() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvLeaveOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mLeaveItems.get(options1);
                mLeavePosition = options1;
                xzqhTv.setText(tx);
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                //自定义布局中的控件初始化及事件处理
                TextView tv_finish = v.findViewById(R.id.tv_finish);
                TextView titleTv = v.findViewById(R.id.titleTv);
                titleTv.setText("选择行政区划");
                tv_finish.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvLeaveOptions.returnData();
                        pvLeaveOptions.dismiss();
                    }
                });

                TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvLeaveOptions.dismiss();
                    }
                });
            }
        })
        .build();
        pvLeaveOptions.setPicker(mLeaveItems);//添加数据
        pvLeaveOptions.show();
    }

    private void loadZrq() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvLeaveOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mZrqItems.get(options1);
                mLeavePosition = options1;
                zrqTv.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择责任区");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLeaveOptions.returnData();
                                pvLeaveOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLeaveOptions.dismiss();
                            }
                        });
                    }
                }).build();
        pvLeaveOptions.setPicker(mZrqItems);//添加数据
        pvLeaveOptions.show();
    }

    private void loadZrr() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvLeaveOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                GridUserModel gum = mZrrItems.get(options1);
                mLeavePosition = options1;
                zrrTv.setText(gum.getName());
                zrrTv.setTag(gum.getId());
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                //自定义布局中的控件初始化及事件处理
                TextView tv_finish = v.findViewById(R.id.tv_finish);
                TextView titleTv = v.findViewById(R.id.titleTv);
                titleTv.setText("选择责任人");
                tv_finish.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvLeaveOptions.returnData();
                        pvLeaveOptions.dismiss();
                    }
                });

                TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvLeaveOptions.dismiss();
                    }
                });
            }
        }).build();

        //创建选择数组
        List<String> mZrrItemsTemp = new ArrayList<>();
        for (GridUserModel gumO: mZrrItems){
            mZrrItemsTemp.add(gumO.getName());
        }
        pvLeaveOptions.setPicker(mZrrItemsTemp);//添加数据
        pvLeaveOptions.show();
    }

}
